package com.hepinghospital.user.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.base.BaseFragment;
import com.hepinghospital.user.eventbus.UpdateFamilyEvent;
import com.hepinghospital.user.ui.JiuzhenCodeActivity;
import com.hepinghospital.user.ui.WebViewActivity;
import com.hepinghospital.user.ui.dialog.ChooseDialog;
import com.hepinghospital.user.ui.dialog.CodeChangeDialog;
import com.hepinghospital.user.ui.dialog.CodeDialog;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.MyFamilyListResponse;
import com.rest.response.YSGCardInfoResponse;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import jz.joyoung.robot.util.UtilString;

/**
 * 检测报告
 *
 * @author lzp
 * @date 2020/3/7
 */

public class CheckRecordFragment extends BaseFragment {
    @BindView(R.id.tv_add_person)
    TextView tvAddPerson;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private MyAdapter adapter;
    private List<MyFamilyListResponse> list = new ArrayList<>();

    private ChooseDialog mChooseDialog;
    private CodeChangeDialog mChangeCodeDialog;

    private MyFamilyListResponse myFamily;

    @SuppressLint("StaticFieldLeak")
    private static CheckRecordFragment checkRecordFragment;

    public static CheckRecordFragment newInstance() {
        if (checkRecordFragment == null) {
            checkRecordFragment = new CheckRecordFragment();
        }
        return checkRecordFragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_check_record;
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        tvAddPerson.setVisibility(View.GONE);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> getFamilyList());
    }

    @Override
    protected void initData() {
        getFamilyList();
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    @Subscribe
    public void updateFamily(UpdateFamilyEvent event) {
        getFamilyList();
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(mContext).inflate(R.layout.item_jiuzhen_person, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                if (list.get(position).isBindingCard != 0) {
                    Bundle bundle = new Bundle();
                    bundle.putString("patientId", list.get(position).patientId);
                    bundle.putString("fromWhere", "CheckRecordFragment");
                    startActivity(WebViewActivity.class, bundle);
                } else {
                    ToastUtil.showToast(mContext, "该患者尚未绑卡，无法查看检查报告");
                }
            });
            holder.tv_name.setText(list.get(position).name);
            if (list.get(position).isBindingCard == 0) {
                holder.tv_type.setText("未绑卡");
                holder.tv_bind.setVisibility(View.VISIBLE);
                holder.iv_qrcode.setVisibility(View.GONE);
                holder.tv_type.setTextColor(ContextCompat.getColor(mContext, R.color.color_F54C4C));
            } else if (list.get(position).isBindingCard == 2) {
                holder.tv_type.setText("审核中");
                holder.tv_bind.setVisibility(View.GONE);
                holder.iv_qrcode.setVisibility(View.VISIBLE);
                holder.tv_type.setTextColor(ContextCompat.getColor(mContext, R.color.commonGrey));
            } else if (list.get(position).isBindingCard == 1) {
                holder.tv_bind.setVisibility(View.GONE);
                holder.iv_qrcode.setVisibility(View.VISIBLE);
                holder.tv_type.setTextColor(ContextCompat.getColor(mContext, R.color.commonGrey));
                if (list.get(position).cardType == 1) {
                    holder.tv_type.setText("自费卡");
                } else if (list.get(position).cardType == 2) {
                    holder.tv_type.setText("医保卡");
                } else if (list.get(position).cardType == 3) {
                    holder.tv_type.setText("自费卡 医保卡");
                }
            }
            if (TextUtils.isEmpty(list.get(position).relation)) {
                holder.tv_relation.setVisibility(View.GONE);
            }
            holder.tv_relation.setText(list.get(position).relation);
            holder.tv_info.setText(list.get(position).sex + list.get(position).age + "岁," + list.get(position).phone);

            if (!UtilString.isEmpty(BaseApplication.avatar)) {
                ImageLoaderHelper.getInstance().setCirclePicture(mContext, holder.iv_head, BaseApplication.avatar);
            } else {
                if ("女".equals(BaseApplication.sex)) {
                    holder.iv_head.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_head_user_woman));
                } else {
                    holder.iv_head.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_head_user_man));
                }
            }
//            GlideUtil.loadImage(mContext, "", holder.iv_head, R.drawable.ic_head_user_man);
            holder.iv_qrcode.setOnClickListener(v -> {
                Intent intent = new Intent(mContext, JiuzhenCodeActivity.class);
                intent.putExtra("patientName", list.get(position).name);
                intent.putExtra("cardNo", list.get(position).ownExpenseNum);
                startActivity(intent);
            });
            holder.tv_bind.setOnClickListener(v -> {
                myFamily = list.get(position);
                showChooseDialog();
            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_type, tv_card_num, tv_info, tv_relation, tv_bind;
            ImageView iv_head, iv_qrcode;

            public Holder(View itemView) {
                super(itemView);
                iv_head = itemView.findViewById(R.id.iv_head);
                iv_qrcode = itemView.findViewById(R.id.iv_qrcode);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_type = itemView.findViewById(R.id.tv_type);
//                tv_card_num = itemView.findViewById(R.id.tv_card_num);
                tv_relation = itemView.findViewById(R.id.tv_relation);
                tv_info = itemView.findViewById(R.id.tv_info);
                tv_bind = itemView.findViewById(R.id.tv_bind);
            }
        }
    }

    private void getFamilyList() {
        RestProxy.getInstance().getMyFamily(BaseApplication.currentUserId, new BaseObserver<List<MyFamilyListResponse>>() {

            @Override
            public void onSuccess(List<MyFamilyListResponse> myFamilyListResponses) {
                refreshLayout.finishRefresh(true);
                list.clear();
                list.addAll(myFamilyListResponses);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                refreshLayout.finishRefresh(false);
            }
        });
    }

    /**
     * 绑卡弹框
     *
     * @time 2020/11/19 13:14
     */
    private void showChooseDialog() {
        mChooseDialog = ChooseDialog.newInstance();
        mChooseDialog.show(getChildFragmentManager(), "mChooseDialog");
        mChooseDialog.setText("是否想要绑定自费就诊卡/医保卡", "绑卡", "暂不绑卡");
        mChooseDialog.setmListener(new ChooseDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                getYSGCardInfo();
            }

            @Override
            public void onCancel() {
            }
        });
    }

    private void getYSGCardInfo() {
        RestProxy.getInstance().getYSGCardInfo(myFamily.patientId, new BaseObserver<YSGCardInfoResponse>() {
            @Override
            public void onSuccess(YSGCardInfoResponse ysgCardInfoResponse) {
                if (ysgCardInfoResponse.operationType == 0) {//曾经创建过卡号
                    showChooseDialog2(ysgCardInfoResponse.phone);
                } else if (ysgCardInfoResponse.operationType == 1) {
                    //手机号不一致，可以直接发送验证码或者去修改手机号
                    showChangeCodeDialog(ysgCardInfoResponse.hosPhoneNo);
                } else if (ysgCardInfoResponse.operationType == 2) {
                    showChooseDialog3(ysgCardInfoResponse.phone);
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }
        });
    }

    private void showChooseDialog2(final String phone) {
        mChooseDialog = ChooseDialog.newInstance();
        mChooseDialog.show(getChildFragmentManager(), "mFinishDialog");
        mChooseDialog.setText("您在温州和平国际医院曾创建过卡号，请关联绑定", "绑卡", "暂不绑卡");
        mChooseDialog.setmListener(new ChooseDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                showCodeDialog(phone, 0);
            }

            @Override
            public void onCancel() {
            }
        });
    }


    private void showChooseDialog3(final String phone) {
        mChooseDialog = ChooseDialog.newInstance();
        mChooseDialog.show(getChildFragmentManager(), "mFinishDialog");
        mChooseDialog.setText("是否在医院里新建自费就诊卡", "新建", "暂不新建");
        mChooseDialog.setmListener(new ChooseDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                showCodeDialog(phone, 2);
            }

            @Override
            public void onCancel() {
            }
        });
    }

    /**
     * 手机号一致，直接发送验证码
     *
     * @time 2020/11/19 14:17
     */
    private void showCodeDialog(String phone, final int type) {
        CodeDialog mCodeDialog = CodeDialog.newInstance();
        mCodeDialog.show(getChildFragmentManager(), "mCodeDialog");
        mCodeDialog.setText(phone);
        mCodeDialog.setmListener(new CodeDialog.OnItemClickListener() {

            @Override
            public void onConfirm(String code) {
                if (type == 0) {
                    bindCard(code, phone);
                } else if (type == 2) {
                    createCard(code);
                }
            }

            @Override
            public void onCancel() {
            }
        });
    }

    /**
     * 手机号不一致，发送验证码或者去修改手机号
     *
     * @time 2020/11/19 14:17
     */
    private void showChangeCodeDialog(String phone) {
        mChangeCodeDialog = CodeChangeDialog.newInstance(myFamily.patientId, myFamily.id, phone);
        mChangeCodeDialog.show(getChildFragmentManager(), "mCodeDialog");
//        mChangeCodeDialog.setPhone( phone );
        mChangeCodeDialog.setmListener(new CodeChangeDialog.OnItemClickListener() {

            @Override
            public void onConfirm(String code) {
                bindCard(code, phone);
            }

            @Override
            public void onCancel() {
            }
        });
    }

    private void bindCard(String code, String hosPhoneNo) {
        RestProxy.getInstance().bindCard(myFamily.patientId, code, hosPhoneNo, new BaseObserver<String>() {
            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onSuccess(String result) {
                getFamilyList();
                ToastUtil.showToast(mContext, "绑定成功");
            }
        });
    }

    private void createCard(String code) {
        RestProxy.getInstance().createCard(myFamily.patientId, code, new BaseObserver<String>() {
            @Override
            public void onSuccess(String result) {
                getFamilyList();
                ToastUtil.showToast(mContext, "新增成功");
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }
        });
    }
}
